package com.techysky.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;

import com.techysky.entity.DataModule;
import com.techysky.entity.MultiMedia;
import com.techysky.repository.DataModuleRepository;
import com.techysky.repository.MultiMediaRepository;

public class HtmlUtils { 
	

	private static final String HREF = "href=\"#";
	private static final String HTML2 = ".html";
	private static Log log=LogFactory.getLog(HtmlUtils.class);
	private static final String TABLENO2 = "%TABLENO%";

	private static final String EXT2 = "%ext%";

	private static final String PATH = "%PATH%";

	private static final String JPG = ".jpg";

	private static final String WRL = ".wrl";

	private static final String UNITY3D = ".unity3d";

	private static final String IMG = "/img/";

	private static final String EXT = ".%ext%";

	private static final String CGM = ".cgm";

	private static final String WMV = ".wmv";

	private static final String AVI = ".avi";

	private static final String MPEG = ".mpeg";

	private static final String MPG = ".mpg";

	private static final String SWF = ".swf";

	private static final String HTML = "/html/";

	private static final String TABLE2 = "table";

	private static final String FIGURE2 = "figure";

	private static final String PICNO2 = "%PICNO%";

	private static final String SEGNO2 = "%SEGNO%";

	private static final String PICID2 = "%picid%";
	
	
	
	/**
 * 在生成的html的基础上替换多媒体，表格等的引用编号
 * @param dmHtml
 * @param multiMediaService
 * @param projectId
 */
public static  String replacHtml(String htmlPath,String htmlName, ApplicationContext ac){
	//要转换的html完整路径
	String dmfile = htmlPath+"\\" +htmlName;
    StringBuilder dmContent=new StringBuilder();
    File file = new File(dmfile);
    BufferedReader br = null;
    if ((file.exists()) && (file.length() > 0L))
    {
      try
      {
        int picid = 0;
        int picno = 0;
        int tableno = 0;
        int segno = 0;
        int figure=1;
        int table=1;
        String tableInfo = "";
        String segInfo = "";
        String content = "";
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
        List<String> list = new ArrayList<>(1024);
        String line0;
        while ((line0 = br.readLine()) != null)
        {
          list.add(line0);
        }
        br.close();
        br = null;
        String parFlag = null;
        String[] strArr = list.toArray(new String[0]);
        Map<String, String> objNumMap = new HashMap<>(128);
        Map<String, String> parRefMap = new HashMap<>(128);	//段落对应关系
        Set<String> outObjSet = new HashSet<>();
        int[] tab = new int[''];
        int[] fig = new int[''];
        Map<String, Integer> objLine = new HashMap<>();
        int count = -1;
        int index;
        for (int i = 0; i < strArr.length; i++)
        {
          String line = strArr[i];
          String refDmCode = getRegGroup(line, "onclick=\"refDM\\('([0-9|A-Z|a-z|-]+)'\\)\">");
          if ((null!=refDmCode) && (!"".equals(refDmCode)))
          {
        	  DataModule refdm=ac.getBean(DataModuleRepository.class).findByDmCode(refDmCode);
        	  if(!ObjectUtils.isEmpty(refdm))
        	  if(null!=refdm.getUrl()&&!"".equals(refdm.getUrl())){
        		  line=line.replaceAll("refDM\\('"+refDmCode+"'\\)\">"+refDmCode+"</a>","refDM\\('"+refDmCode+"'\\);return false;\">"+refdm.getTitle()+"</a>");
        	  }
        	  else{
        		  line=line.replaceAll(">"+refDmCode+"</a>",">"+refdm.getTitle()+"</a>");
        	  }
          }
          line = parseMedia(ac,strArr, i, line);
          index = line.indexOf("name=\"");
          if (index != -1)
          {
            String name = line.substring(index + 6, line.indexOf('"', index + 6));
          if(name.equals(FIGURE2)) {
        	  line=line.replaceAll("多媒体", "多媒体"/*+figure*/);
        	  figure++;
          }else if(name.equals(TABLE2)) {
        	  line=line.replaceAll("表格", "表格"/*+table*/);
        	  table++;
          }
          }
          if (line.indexOf(PICID2) >= 0)
          {
            picid++;
            line = line.replaceAll(PICID2, "pic" + picid);
          }
          if (line.indexOf(SEGNO2) >= 0)
          {
            segno++;
            line = line.replaceAll(SEGNO2, String.valueOf(segno));
          }
          if (line.indexOf(PICNO2) >= 0)
          {
            picno++;
            fig[picno] = i;
            getRegGroup(line, 
              "%PICNO%(.*?)[<][/]").replace('"', '\'');
            line = line.replaceAll(PICNO2, String.valueOf(picno));
          }
          if (line.indexOf(TABLENO2) >= 0)
          {
            tableno++;
            tab[tableno] = i;
            String group = getRegGroup(line, 
              "%TABLENO%(.*?)[<][/]").replace('"', '\'');
            String text = group;
            if ("".equals(text)) {
              text = "表 " + tableno;
            }
            tableInfo = 
              tableInfo + ",{\"id\":\"table" + tableno + "\",\"text\":\"" + text + "\"}";
            line = line.replaceAll(TABLENO2, "<span id=\"table" + 
              tableno + "\">" + tableno + "</span>");
          }
         
          if (line.indexOf("{{") >= 0)
          {
        	  String parRefString = getRegGroup(line, "<p[\\s]{1,3}class=\"subtitle\"[\\s]{1,3}parhref=\"([a-z|A-Z|0-9|-]{1,9}\">\\{\\{[0-9]{1,2})<").replace("\">{{", ",");
              if ((null!=parRefString) && (!"".equals(parRefString))){
            	  String a[]=parRefString.split(",");
            	  parRefMap.put(a[0], a[1]);
              }
            segno++;
            int index1 = line.indexOf("{{");
            int index2 = line.indexOf("}}");
            if (index2 == -1) {
              index2 = line.length();
            }
            String segtext = line.substring(index1 + 2, index2)
              .replace("[\"|\n|\r]", "").replace('"', '\'');
            segInfo = segInfo + ",{\"id\":\"seg" + segno + "\",\"text\":\"" + 
              segtext + "\"}";
            line = line.replaceAll("\\{\\{", "<span id=\"seg" + 
              segno + "\">");
          }
          if (line.indexOf("}}") >= 0) {
            line = line.replaceAll("\\}\\}", "</span>");
          }
          if ((parFlag != null) && (count >= 0))
          {
            String parNo = getRegGroup(line, "[>]([0-9\\.]+)[<]");
            if (!ObjectUtils.isEmpty(parNo))
            {
              objNumMap.put(parFlag, parNo);
              parFlag = null;
              count = -1;
            }
            count--;
          }
          String parname = getRegGroup(line, "[<]a name[=][\"]([a-z]*[-][0-9]*)[\"][>]");
          if ((parname != null) && ((parname.startsWith("pro")) || (parname.startsWith("stp"))))
          {
            count = 3;
            parFlag = parname;
            String parNo = getRegGroup(line, "[>]([0-9\\.]+)[<]");
            if (!ObjectUtils.isEmpty(parNo))
            {
              objNumMap.put(parFlag, parNo);
              parFlag = null;
              count = -1;
            }
          }
          else if (count < 0)
          {
            parFlag = null;
          }
          String outObj = getRegGroup(line, "[/]([a-zA-Z0-9-_]*[.]htm[^>]*inner_id[=][a-z]{3}[-][0-9a-zA-Z-]*)[\"]");
          if (!ObjectUtils.isEmpty(outObj))
          {
            String outDmc = outObj.substring(0, outObj.indexOf(HTML2));
            String outObjId = outObj.substring(outObj.lastIndexOf('=') + 1);
            outObjSet.add(outDmc + "::" + outObjId);
          }
          strArr[i] = line;
        }
      
        Integer line;
        if (!objLine.isEmpty())
        {
          Set<Map.Entry<String, Integer>> set = objLine.entrySet();
          for (Map.Entry<String, Integer> e : set) {
            if (e.getKey().startsWith("fig"))
            {
              line = e.getValue();
              for (int i = 1; i < fig.length; i++)
              {
                if (fig[i] == 0) {
                  break;
                }
                if (fig[i] >= line.intValue())
                {
                  objNumMap.put((String)e.getKey(), String.valueOf(i));
                  break;
                }
              }
            }
            else if (e.getKey().startsWith("tab"))
            {
              line = e.getValue();
              for (int i = 1; i < tab.length; i++)
              {
                if (tab[i] == 0) {
                  break;
                }
                if (tab[i] + 2 >= line.intValue())
                {
                  objNumMap.put((String)e.getKey(), String.valueOf(i));
                  break;
                }
              }
            }
          }
        }
        boolean pflag = !objNumMap.isEmpty();
        for (String line1 : strArr)
        {
          if (pflag)
          {
            Set<String> finds = getRegGroupList(line1, " href[=][\"]#([a-z]*[-][0-9a-zA-Z-]*)[\"][>]");
            for (String innerLinkId : finds) {
              if (!ObjectUtils.isEmpty(innerLinkId))
              {
                String objNo = objNumMap.get(innerLinkId);
                if (objNo == null) {
                  objNo = objNumMap.get(innerLinkId.substring(0, 8));
                }
                if (objNo != null)
                {
                  String type = "多媒体";
                  /*if (innerLinkId.startsWith("par"))
                  {
                    type = "段落";
                  }
                  else */
                 if (innerLinkId.startsWith("tab"))
                  {
                    type = "表格";
                  }
                  else if (innerLinkId.startsWith("pro"))
                  {
                    type = "程序";
                  }
                  else if (innerLinkId.startsWith("stp"))
                  {
                    type = "步骤";
                  }
                  else if ((innerLinkId.startsWith("fig")) && 
                    (innerLinkId.indexOf("hot") != -1))
                  {
                    String sub = innerLinkId.substring(innerLinkId.lastIndexOf('-') + 1);
                    while ((sub.length() > 1) && (sub.charAt(0) == '0')) {
                      sub = sub.substring(1);
                    }
                    objNo = objNo + "[" + sub + "]";
                  }
                  line1 = line1.replace(" href=\"#" + innerLinkId + "\">" + type, " href=\"#" + innerLinkId + "\">" + type + " " + objNo);
                }
              }
            }
          }
          content = content + line1 + '\n';
        }
        //正文中表格编号对应
        Set<String> tableIds = getRegGroupList(content.replaceAll("\r|\n", ""), "(<span[\\s]{1,3}id=\"table[0-9]{1,3}\">[0-9]{1,3}</span>.{1,20}<a[\\s]{1,3}name=\"[a-z|A-Z|0-9]{1,6}\"></a>)");
        for (String tableId : tableIds) {
        	String idNum=getRegGroup(tableId,">([0-9]+)<");
        	String aName=getRegGroup(tableId,"<a name=\"(.+)\">");
        	content=content.replaceAll(HREF+aName+"\">表格", HREF+aName+"\">表格"+idNum);
        }
      //正文中多媒体编号对应
        Set<String> mulIds = getRegGroupList(content.replaceAll("\r|\n", ""), "(<div[\\s]{1,3}class=\"textcenter\"[\\s]{1,3}idno=\"[a-z|A-Z|0-9]{1,6}\">[\\s]{0,5}多媒体[\\u4e00-\\u9fa5|a-z|A-Z|0-9|\\s]{0,20}</div>)");
        for (String mulId : mulIds) {
        	String idNum=getRegGroup(mulId,"多媒体[\\s]{0,3}([0-9]+)[\\s]{1,3}");
        	String aName=getRegGroup(mulId,"idno=\"([a-z|A-Z|0-9]{1,6})\"");
        	content=content.replaceAll(HREF+aName+"\">多媒体", HREF+aName+"\">多媒体"+idNum);
        }
        //段落编号对应
        if(!parRefMap.isEmpty()){
        	for (Map.Entry<String, String> entry : parRefMap.entrySet()) {  
        	    content=content.replaceAll("href=\"#"+entry.getKey()+"\">段落", "href=\"#"+entry.getKey()+"\">段落"+entry.getValue());
        	} 
        }
        
        String lines=content.substring(content.indexOf("<body>"),content.lastIndexOf("</body>")).replaceAll("</?[^>]+>", "").replaceAll("<a>\\s*|\t|\r|\n</a>", "").replaceAll(" ", "");
        dmContent.append(lines);
        write(dmfile, content);
       
        File newhtm = new File(htmlPath + File.separatorChar + htmlName.substring(0,htmlName.indexOf('_'))+HTML2);
        if (newhtm.exists()) {
          newhtm.delete();
          newhtm.createNewFile();
          FileCopyUtils.copy(file, newhtm);
        }else
        {
        	 newhtm.createNewFile();
             FileCopyUtils.copy(file, newhtm);
        }
      }
      catch (Exception e)
      {
    	//  log.info(e);
    	  e.printStackTrace();
      }
      try
      {
        if (br != null) 
        br.close();
      }
      catch (Exception localException3) {
    	 // log.info(localException3);
    	  localException3.printStackTrace();
      }
    }
    else
    {
      write(
        htmlPath + File.separatorChar +htmlName.substring(htmlName.indexOf('-')), 
        "<html>\n<head>\n<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<META content=\"text/html; charset=utf-16\" http-equiv=\"Content-Type\">\n</head>\n<body>\n<div id=\"content\">温馨提示:请重新应用模板</div>\n</body>\n</html>");
    }
    return dmContent.toString();
  
}


/**
 * 单纯解析多媒体
 * @param folderName
 * @param multiMediaService
 * @param projectId
 * @param strArr
 * @param i
 * @param line
 * @return
 */
private static String parseMedia(ApplicationContext ac, 
		String[] strArr, int i, String line1) {
	String line=line1;
	 if(line.contains("<html>")) {
   	  line=line.replaceAll("<html>","<!DOCTYPE html> <html>");
     }
	if(line.contains(PATH)&&line.contains(EXT2)) {
		  String icn=line.substring(line.indexOf(PATH)+7,line.indexOf(EXT2)-1);
		  MultiMedia media=ac.getBean(MultiMediaRepository.class).findByIcn(icn);
		  if(media!=null)
		  if(media.getExtName().equalsIgnoreCase(CGM)) {
			  if(line.contains("<object")||line.contains("id=\"hiddendiv\"")){  //海军ipd调整左图右文字
				  line=line.replaceAll(EXT, media.getExtName());
			  }
			  else{
			  strArr[i-1]="<a onclick=\"openCgm('"+media.getCode()+"',\'/html/"+icn+media.getExtName()+"\','"+media.getCode()+"')\"  href=\"javascript:void(0)\">";
			  line=line.replaceAll(PATH, IMG).replaceAll(icn, "CGM.png").replaceAll(EXT, "");
			  strArr[i+1]="</a>";
			  }
		  }else if(media.getExtName().equalsIgnoreCase(SWF)){
			  strArr[i-1]=" ";
			  line=flash(HTML+icn+media.getExtName());
			  strArr[i+1]=" ";
		  }else if(media.getExtName().equalsIgnoreCase(UNITY3D)){
			  strArr[i-1]="<a onclick=\"openU3D('ICN-CYJ-A-000000-T-TECHY-00005-A-01-01','','','',\'/html/"+icn+media.getExtName()+"','"+media.getCode()+"')\" href=\"javascript:void(0)\">";
			  line=line.replaceAll(PATH, IMG).replaceAll(icn, "3D.png").replaceAll(EXT, "");
			  strArr[i+1]="</a>";
		  }else if(media.getExtName().equalsIgnoreCase(WRL)){
			  strArr[i-1]="<a onclick=\"openWrl('"+media.getId()+"',\'"+HTML+icn+media.getExtName()+"','"+media.getCode()+"')\" href=\"javascript:void(0)\">";
			  line=line.replaceAll(PATH, IMG).replaceAll(icn, "3D.png").replaceAll(EXT, "");
			  strArr[i+1]="</a>";
		  }else if(media.getExtName().equalsIgnoreCase(MPG)||media.getExtName().equalsIgnoreCase(MPEG)||media.getExtName().equalsIgnoreCase(AVI)||media.getExtName().equalsIgnoreCase(WMV)){
			  strArr[i-1]=" ";
			  line=video(HTML+icn+media.getExtName());
			  strArr[i+1]=" ";
		  }else if(media.getExtName().equalsIgnoreCase(JPG))
		  {
			  if(media.getExtName().equals(JPG))
			  {
				  strArr[i-1]=" ";
				  line=line.replaceAll(icn, icn+JPG).replaceAll(EXT, "");
				  strArr[i+1]=" ";
			  }
			  else
			  {
				  strArr[i-1]=" ";
				  line=line.replaceAll(icn, icn+".JPG").replaceAll(EXT, "");
				  strArr[i+1]=" ";
			  }
			  
		  }
		  else {
			  line=line.replaceAll(EXT, media.getExtName());
		  }
		  }
    line = line.replaceAll(PATH,HTML).replaceAll("%0A","").replaceAll("%09","");
	return line;
}

private static void write(String file, String context)
{
  PrintWriter pw = null;
  try
  {
    pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
      file), "utf-8"));
    pw.write(context);
    pw.flush();
    pw.close();
  }
  catch (Exception e)
  {
	  //log.info(e);
	  e.printStackTrace();
  }
}



private static String getRegGroup(String input, String regx)
{
  try
  {
    Pattern p = Pattern.compile(regx);
    Matcher m = p.matcher(input);
    if (m.find())
    {
      String group = m.group(1);
      if (group != null) {
        return group;
      }
    }
  }
  catch (Exception e)
  {
	  //log.info(e);
	  e.printStackTrace();
  }
  return "";
}

private static Set<String> getRegGroupList(String input, String regx)
{
  Set<String> list = new HashSet<>();
  try
  {
    Pattern p = Pattern.compile(regx);
    Matcher m = p.matcher(input);
    while (m.find())
    {
      String group = m.group(1);
      if (group != null) {
        list.add(group);
      }
    }
  }
  catch (Exception e)
  {
	 // log.info(e);
	  e.printStackTrace();
  }
  return list;
}

/**
 * 视频文件需要拼接的html
 * @return
 */
public static String video(String videoUrl) {
	StringBuilder content=new StringBuilder();
	content.append("<object id=\"MediaPlayer\" width=\"100%\"  height=\"350px\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" type=\"application/x-oleobject\">\r\n");
	content.append("<param name=\"ShowPositionControls\" value=\"0\"/>\r\n");
	content.append("<param name=\"windowlessVideo\" value=\"1\"/>\r\n");
	content.append("<param name=\"AutoStart\" value=\"0\" />\r\n");
	content.append("<param name=\"EnableContextMenu\" value=\"0\">\r\n");
	content.append("<param name=\"URL\" value=\""+videoUrl+"\" />\r\n");
	content.append("</object>");
	return content.toString();
}

public static String flash(String swfPath) {
	StringBuilder content=new StringBuilder();
	content.append("<object id=\"forfun\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" width=\"100%\"  height=\"350px\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\">\r\n");
	content.append("<param name=\"movie\" value=\""+swfPath+"\">\r\n\"");
	content.append("<param name=\"quality\" value=\"high\">\r\n");
	content.append("<param name=\"bgcolor\" value=\"#F0F0F0\">\r\n");
	content.append("<param name=\"menu\" value=\"false\">\r\n");
	content.append("<param name=\"wmode\" value=\"opaque\">");
	content.append("<param name=\"FlashVars\" value=\"\">\r\n");
	content.append("<param name=\"allowScriptAccess\" value=\"sameDomain\">\r\n");
	content.append("</object>");
	return content.toString();
}
}
